package com.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述:
 *
 * @author luzhongfu
 * Created by lucky on 2020-06-01 2:21 PM
 */
public class MyCondition {


    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        User user = new User("123456", 100000);
        executorService.execute(new Save(user,1000));
        executorService.execute(new Draw(user,5000));
        executorService.execute(new Save(user,10000));
        executorService.execute(new Draw(user,20000));
        executorService.shutdown();

    }

    static class Save implements Runnable{

        User user;

        int money;

        public Save(User user, int money) {
            this.user = user;
            this.money = money;
        }

        @Override
        public void run() {
            user.save(money);
        }
    }

    static class Draw implements Runnable{

        User user;

        int money;

        public Draw(User user, int money) {
            this.user = user;
            this.money = money;
        }
        @Override
        public void run() {
            user.draw(money);
        }
    }

    static class User {
        private Lock lock = new ReentrantLock();
        private Condition d_lock = lock.newCondition();
        private Condition s_lock = lock.newCondition();

        private String account;

        private int count;

        public User(String account, int count) {
            this.account = account;
            this.count = count;
        }

        public void save(int money){
            lock.lock();
            try {
                if(money > 0){
                    count += money;
                    System.out.println("存入金额:"+money + " 现有count:"+count);
                }
                d_lock.signalAll();
            }finally {
                lock.unlock();
            }
        }

        public void draw(int money){
            lock.lock();
            try {
                if(count < money){
                    try {
                        d_lock.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    count -= money;
                    System.out.println("取出金额:"+money + " 现有 count:"+count);
                }
                s_lock.signalAll();
            }catch (Exception e){
            }finally {
                lock.unlock();
            }
        }
    }
}
